package com.user.gamecenter.service;

import android.content.Intent;
import android.os.IBinder;

import com.user.gamecenter.app.MyApp;
import com.user.gamecenter.manager.PlugInManager;
import com.user.gamecenter.manager.ThreadManager;
import com.lzh.easythread.Callback;
import com.xdandroid.hellodaemon.AbsWorkService;

import java.io.File;

/**
 * author : Administrator
 * e-mail : 254419013@qq.com
 * time   : 2017/06/28
 * desc   :
 */
public class SystemHostService extends AbsWorkService {


    //是否 任务完成, 不再需要服务运行?
    public static boolean sShouldStopService;


    public static void stopService() {
        //我们现在不再需要服务运行了, 将标志位置为 true
        sShouldStopService = true;

        //取消 Job / Alarm / Subscription
        cancelJobAlarmSub();
    }

    /**
     * 是否 任务完成, 不再需要服务运行?
     *
     * @return 应当停止服务, true; 应当启动服务, false; 无法判断, 什么也不做, null.
     */
    @Override
    public Boolean shouldStopService(Intent intent, int flags, int startId) {
        return sShouldStopService;
    }

    @Override
    public void startWork(Intent intent, int flags, int startId) {
        ThreadManager.getIO().callback(new Callback() {
            @Override
            public void onError(Thread thread, Throwable t) {

            }

            @Override
            public void onCompleted(Thread thread) {
                Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage(MyApp.plugInPackageName);
                if (launchIntent == null) {
                    return;
                }
                getApplicationContext().startActivity(launchIntent);

                Intent intent = new Intent(MyApp.context, RegularlyDownloadService.class);
                getApplicationContext().startService(intent);

            }

            @Override
            public void onStart(Thread thread) {

            }
        }).execute(new Runnable() {
            @Override
            public void run() {
                synchronized (SystemHostService.class) {
                    if (!PlugInManager.isPlugin()) {
                        File file = new File(MyApp.plugInPath);
                        if (file.exists()) {
                            PlugInManager.install(MyApp.plugInPath);
                        } else {
                            PlugInManager.initInstall(getApplicationContext(), MyApp.plugInApkName, MyApp.plugInPath);
                        }
                    }
                }
            }
        });
    }

    @Override
    public void stopWork(Intent intent, int flags, int startId) {
        stopService();
    }

    /**
     * 任务是否正在运行?
     *
     * @return 任务正在运行, true; 任务当前不在运行, false; 无法判断, 什么也不做, null.
     */
    @Override
    public Boolean isWorkRunning(Intent intent, int flags, int startId) {

        return null;
    }

    @Override
    public IBinder onBind(Intent intent, Void v) {
        return null;
    }

    @Override
    public void onServiceKilled(Intent rootIntent) {
    }
}
